﻿
module internal Octopus.RemoteHpcPS.Utility

open System.Management


//
//--------------- remote function invocation
//

let private hpcpsPort = 17500

let execute_remote_function hpcpsServer (functionInfo:string array) =
  let client = new System.Net.Sockets.TcpClient(hpcpsServer, hpcpsPort)
  try
    use stream = client.GetStream()
    use sw = new System.IO.StreamWriter(stream)
    use sr = new System.IO.StreamReader(stream)
    functionInfo |> Array.iter (fun x -> sw.WriteLine(x)) 
    sw.Flush()
    let result = System.Boolean.Parse(sr.ReadLine())
    if not(result) then failwith (sr.ReadLine())
    else ()
  finally
    client.Close()

let execute_remote_function_withReturn hpcpsServer (functionInfo:string array) =
  let client = new System.Net.Sockets.TcpClient(hpcpsServer, hpcpsPort)
  try
    use stream = client.GetStream()
    use sw = new System.IO.StreamWriter(stream)
    use sr = new System.IO.StreamReader(stream)
    functionInfo |> Array.iter (fun x -> sw.WriteLine(x)) 
    sw.Flush()
    let result = System.Boolean.Parse(sr.ReadLine())  
    if not(result) then failwith (sr.ReadLine())
    else sr.ReadLine()
  finally
    client.Close()


let execute_remote_function_withArrayReturn hpcpsServer (functionInfo:string array) =
  let client = new System.Net.Sockets.TcpClient(hpcpsServer, hpcpsPort)
  try
    use stream = client.GetStream()
    use sw = new System.IO.StreamWriter(stream)
    use sr = new System.IO.StreamReader(stream)
    functionInfo |> Array.iter (fun x -> sw.WriteLine(x)) 
    sw.Flush()
    let result = System.Boolean.Parse(sr.ReadLine())  
    if not(result) then failwith (sr.ReadLine())
    else
      let arraySize = System.Int32.Parse(sr.ReadLine())
      [| for i = 1 to arraySize do yield sr.ReadLine() |]
  finally
    client.Close()


//---------------------------

module internal ObjSerializer =
  let serialize (obj:obj) =
    let formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    use stream = new System.IO.MemoryStream()
    formatter.Serialize(stream, obj)
    stream.Seek(0L, System.IO.SeekOrigin.Begin) |> ignore
    let data = Array.zeroCreate<byte> (int stream.Length)
    stream.Read(data, 0, (int stream.Length)) |> ignore
    System.Convert.ToBase64String(data)

  let deserialize str =
    let data = System.Convert.FromBase64String(str)
    use stream = new System.IO.MemoryStream()
    stream.Write(data, 0, data.Length) |> ignore
    stream.Seek(0L, System.IO.SeekOrigin.Begin) |> ignore
    let formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    formatter.Deserialize(stream)

//---------------------------
